/**
 * author：是三金呀
 * 微信号：junxin367
 * date：2024-11-9 20:43:57
 */

import { XinConfig } from "../../config/XinConfig";
import { TableName } from "./enum/Enum";
import { LeaderboardService } from "./zfbService/LeaderboardService";
import { ZfbCloud } from "./zfbService/ZfbCloud";
const wx = window['wx'];

export class RankUtil {
    /***************** 支付宝云函数参数 ******************/
    private static _leaderboardId = XinConfig.zfbConfig.leaderboardId;
    private static _secretId = XinConfig.zfbConfig.secretId;
    private static _secretKey = XinConfig.zfbConfig.secretKey;
    private static _appId = XinConfig.zfbConfig.appId;
    private static _envId = XinConfig.zfbConfig.envId;
    private static _leaderboardType = XinConfig.zfbConfig.leaderboardType;

    // 存储单例实例    
    private static _instance: RankUtil;
    // 存储LeaderboardService实例  
    private static _leaderboardService: LeaderboardService;

    // 私有构造函数，确保外部无法实例化  
    private constructor() {
        // 初始化LeaderboardService  
        RankUtil._leaderboardService = new ZfbCloud(RankUtil._secretId, RankUtil._secretKey, RankUtil._appId, RankUtil._envId).callLeaderboardService();
    }

    // 获取单例实例  
    static getInstance(): RankUtil {
        if (!RankUtil._instance) {
            RankUtil._instance = new RankUtil();
        }
        return RankUtil._instance;
    }

    /**  
     * 提交或者更新分数（大于历史分数才更新）  
     * @param openid 用户uid  
     * @param score 分数  
     */
    async replaceScore(openid: string, userProFile: {}, score: number): Promise<any> {
        const cloudKey = "_CLOUD_score";
        const heightScore = wx.getStorageSync(cloudKey) || 0;
        if (score < heightScore) {
            return;
        }

        return new Promise(async (resolve, reject) => {
            // 返回Promise以处理异步操作  
            try {
                const data: any = await RankUtil._leaderboardService.replaceScore({
                    playerId: openid,
                    playerInfo: userProFile,
                    leaderboardId: RankUtil._leaderboardId,
                    leaderboardType: TableName[RankUtil._leaderboardType],
                    score: score,
                });

                resolve(data)
            } catch (error) {
                // 错误处理逻辑  
                console.error('Error updating score:', error);
                reject(error);
            }
        })
    }


    /**
     * 获取排行榜数据
     * @param startRank 
     * @param count 
     * @param sort 
     * @returns 
     */
    getRankList(openId?: string, startRank?: number, count?: number, sort?: number) {
        return new Promise((resolve, reject) => {
            RankUtil._leaderboardService.getLeaderboardTopRank({
                playerId: openId,
                leaderboardId: RankUtil._leaderboardId,
                leaderboardType: TableName[RankUtil._leaderboardType],
                startRank: startRank,
                count: count,
                sort: sort
            }).then((res: any) => {
                if (res?.data) {
                    resolve(res.data)
                }
                resolve(null);
            }).catch((e: any) => {
                reject(e)
            })
        })
    }
}